<template>
  <div class="userManagement-container view flex-row align-start">
    <div class="m-r-15 minw300" style="margin-top: 5px">
      <div
        style="
          text-align: right;
          margin-bottom: 10px;
          margin-top: 10px;
          margin-right: 10px;
        "
      >
        <el-button type="primary" plain @click="showAddFenzu = true">
          + 添加组
        </el-button>
      </div>

      <tree
        :nodes="nodes"
        class="c-ztree"
        ref="treeAuth"
        @onClick="selectTree"
        :setting="setting"
        @onCreated="handleCreated"
      />
    </div>

    <div class="flex-1" style="width: calc(100% - 400px)">
      <vab-query-form>
        <vab-query-form-left-panel :span="12">
          <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
            添加
          </el-button>
        </vab-query-form-left-panel>
        <vab-query-form-right-panel :span="12">
          <el-form :inline="true" :model="queryForm" @submit.native.prevent>
            <el-form-item>
              <el-input
                v-model.trim="queryForm.username"
                placeholder="请输入用户名"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button
                icon="el-icon-search"
                type="primary"
                @click="queryData"
              >
                查询
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-right-panel>
      </vab-query-form>

      <div>
        <el-tabs v-model="activeName" type="card" @tab-click="changeTab">
          <el-tab-pane label="组管理员" name="1">
            <el-table
              v-loading="listLoading"
              :data="list"
              border
              :height="getHg"
              :max-height="getHg"
              :element-loading-text="elementLoadingText"
              @selection-change="setSelectRows"
            >
              <el-table-column
                show-overflow-tooltip
                prop="id"
                label="id"
              ></el-table-column>
              <el-table-column
                show-overflow-tooltip
                prop="account"
                label="账号"
              ></el-table-column>
              <el-table-column
                show-overflow-tooltip
                prop="username"
                label="昵称"
              ></el-table-column>

              <el-table-column show-overflow-tooltip label="权限" width="350">
                <template #default="{ row }">
                  <div class="view flex-row flex-wrap">
                    <div
                      v-for="(item, index) in row.permissions"
                      :key="index"
                      class="w100 m-b-15"
                    >
                      <el-tag>
                        {{ item }}
                      </el-tag>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="createtime"
                width="150"
                label="修改时间"
              >
                <template #default="{ row }">
                  <div>
                    {{
                      $dayjs.unix(row.createtime).format('YYYY-MM-DD HH:mm:ss')
                    }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                show-overflow-tooltip
                label="操作"
                width="180"
              >
                <template #default="{ row }">
                  <el-button type="text" @click="handleEdit(row)">
                    编辑
                  </el-button>

                  <el-button type="text" @click="handleViewer(row)">
                    设置监控人员
                  </el-button>

                  <el-button type="text" @click="handleDelete(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="子账户" name="2">
            <el-table
              border
              v-loading="listLoading"
              :data="list"
              :height="getHg"
              :max-height="getHg"
              :element-loading-text="elementLoadingText"
              @selection-change="setSelectRows"
            >
              <el-table-column
                show-overflow-tooltip
                prop="id"
                width="60"
                label="id"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="username"
                width="100"
                align="center"
                label="用户名"
              ></el-table-column>
              <el-table-column
                show-overflow-tooltip
                prop="nickname"
                align="center"
                label="昵称"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="group"
                align="center"
                label="分组"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="feeTemp"
                align="center"
                label="手续费模板"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="marginTemp"
                label="保证金模板"
                align="center"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="fkTemp"
                align="center"
                label="风控模板"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="hlTemp"
                align="center"
                label="汇率模板"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="risk"
                align="center"
                label="风险度"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="money"
                align="center"
                label="可用资金"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="sumrj"
                align="center"
                min-width="150"
                label="当日入金"
              >
                <template #default="{ row }">
                  <div class="view flex-row">
                    当日入金{{ row.sumrj || 0 }}元 / {{ row.countrj || 0 }}笔
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="sumrj"
                align="center"
                min-width="150"
                label="当日出金"
              >
                <template #default="{ row }">
                  <div class="view flex-row">
                    当日出金{{ row.sumcj || 0 }}元 / {{ row.countcj || 0 }}笔
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="margin"
                align="center"
                min-width="100"
                label="占用保证金"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="freezemargin"
                min-width="100"
                align="center"
                label="冻结保证金"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="flootyk"
                align="center"
                label="浮动盈亏"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                min-width="100"
                prop="dayyk"
                align="center"
                label="当日平仓盈亏"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="yk"
                align="center"
                label="总盈亏"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="fee"
                align="center"
                label="手续费"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                prop="feeall"
                align="center"
                min-width="120"
                label="累计手续费"
              ></el-table-column>

              <el-table-column
                show-overflow-tooltip
                fixed="right"
                label="操作"
                width="270"
              >
                <template #default="{ row }">
                  <el-button type="text" @click="reposit(row)">
                    出入金
                  </el-button>

                  <el-button type="text" @click="viewposit(row)">
                    出入金情况
                  </el-button>

                  <el-button type="text" @click="handleEdit(row)">
                    编辑
                  </el-button>

                  <el-button type="text" @click="handleMove(row)">
                    移动分组
                  </el-button>

                  <el-button type="text" @click="handleDelete1(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 出入金 -->
    <rujin ref="churu" @fetch-data="queryData"></rujin>
    <moveGroup ref="moveGroup" @fetch-data="queryData" />
    <!-- 添加监控人员 -->
    <editViewer ref="viewer" @fetch-data="queryData"></editViewer>
    <!-- 添加人员-->
    <edit ref="edit" @fetch-data="queryData"></edit>
    <editChild ref="editChild" @fetch-data="queryData"></editChild>
    <!-- 分组添加 -->
    <el-dialog title="添加分组" :visible.sync="showAddFenzu" width="30%">
      <div>
        <div class="view flex-row align-center m-b-20">
          <div class="w80">名称：</div>
          <el-input
            placeholder="请输入名称"
            v-model="info.groupname"
            clearable
          ></el-input>
        </div>

        <div class="view flex-row align-center">
          <div class="w80">备注：</div>
          <el-input
            placeholder="请输入备注"
            v-model="info.note"
            clearable
          ></el-input>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button
          type="primary"
          @click="addGroupHandle"
          :loading="addGroupLoading"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>

    <el-dialog title="出入金情况" :visible.sync="viewShow" width="70%">
      <div>
        <el-table
          border
          :data="viewlist"
          :element-loading-text="elementLoadingText"
        >
          <el-table-column
            show-overflow-tooltip
            prop="curreny"
            label="币种"
          ></el-table-column>

          <el-table-column
            show-overflow-tooltip
            prop="bz"
            label="币种名称"
          ></el-table-column>

          <el-table-column
            show-overflow-tooltip
            prop="startdeposit"
            label="期初结存"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="equity"
            label="客户权益"
          ></el-table-column>

          <el-table-column
            show-overflow-tooltip
            prop="availablefunds"
            label="可用资金"
          ></el-table-column>

          <el-table-column
            show-overflow-tooltip
            prop="margins"
            label="保证金占用"
          ></el-table-column>

          <el-table-column
            show-overflow-tooltip
            prop="dsfunds"
            label="出入金"
          ></el-table-column>

          <el-table-column
            show-overflow-tooltip
            prop="fees"
            label="手续费"
          ></el-table-column>

          <el-table-column
            show-overflow-tooltip
            prop="yk"
            label="盈亏"
          ></el-table-column>

          <el-table-column
            show-overflow-tooltip
            prop="createtime"
            width="150"
            label="修改时间"
          >
            <template #default="{ row }">
              <div>
                {{ $dayjs.unix(row.createtime).format('YYYY-MM-DD HH:mm:ss') }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="addGroupHandle"
          :loading="addGroupLoading"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getList,
    doDelete,
    addGroup,
    delGroup,
    editgroup,
    getUserlist,
    getMarginlist,
    getFeelist,
    getRatelist,
    getWclist,
    dslist,
    deluser,
  } from '@/api/userManagement'
  import { getGrouplist, getAuthList } from '@/api/ad'
  import rujin from './components/rujin'
  import Edit from './components/UserManagementEdit'
  import editViewer from './components/editViewer'
  import moveGroup from './components/moveGroup'
  import editChild from './components/UserManagementEditChild'
  import tree from 'vue-giant-tree'
  import $ from 'jquery'
  export default {
    name: 'UserManagement',
    components: { Edit, tree, editChild, rujin, editViewer, moveGroup },
    data() {
      return {
        viewShow: false,
        authlist: [],
        fkList: [],
        hlList: [],
        zyzsList: [],
        viewlist: [],
        marginList: [],
        ztreeObj: null,
        addGroupLoading: false,
        showAddFenzu: false,
        info: {
          groupname: '',
          note: '',
        },
        setting: {
          data: {
            simpleData: {
              enable: true,
              pIdKey: 'pid',
            },
          },
          view: {
            showIcon: false,
            addHoverDom: this.addHoverDom,
            removeHoverDom: this.removeHoverDom,
          },
        },
        nodes: [],
        activeName: '1',
        grouplist: [], // 组管理员账号数据
        list: null,
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        elementLoadingText: '正在加载...',
        queryForm: {
          username: '',
          pageNo: 1,
          pageSize: 10,
          groupid: '',
        },
        getH: window.innerHeight - 50,
        getHg: window.innerHeight - 300,
      }
    },
    computed: {
      // getHg() {
      //   return window.innerHeight - 300
      // },
      // getH() {
      //   return window.innerHeight - 50
      // },
    },
    created() {
      this.getAllList()
      $(window).resize(() => {
        this.getH = window.innerHeight - 50
        this.getHg = window.innerHeight - 300
      })
    },
    methods: {
      handleViewer(row) {
        this.$refs['viewer'].showEdit(row)
      },
      viewposit(row) {
        dslist({ uid: row.id }).then((res) => {
          let arr = []
          for (let key in res.data) {
            res.data[key]['curreny'] = key
            arr.push(res.data[key])
          }
          this.viewlist = arr
          this.viewShow = true
        })
      },
      reposit(row) {
        row.nickName = row.nickname
        row.account = row.username
        this.$refs['churu'].showEdit(row)
      },
      handleMove(row) {
        this.$refs.moveGroup.showEdit({ group_id: row.group_id, uid: row.id })
      },
      async getAllList() {
        const arr = await Promise.all([
          getMarginlist({}),
          getFeelist({}),
          getRatelist({}),
          getWclist({}),
        ])
        this.marginList = arr[0].data.map((item) => {
          let da = {}
          da.label = item.name
          da.value = item.id
          return da
        })
        this.feeList = arr[1].data.map((item) => {
          let da = {}
          da.label = item.name
          da.value = item.id
          return da
        })
        this.hlList = arr[2].data.map((item) => {
          let da = {}
          da.label = item.name
          da.value = item.id
          return da
        })
        this.fkList = arr[3].data.map((item) => {
          let da = {}
          da.label = item.name
          da.value = item.id
          return da
        })
        this.getGroupListData()
        this.getAuthListAll()
      },
      changeTab(tab) {
        this.queryData()
      },
      cancel() {
        this.info = {
          groupname: '',
          note: '',
        }
        this.showAddFenzu = false
      },
      selectTree() {
        let node = this.ztreeObj.getSelectedNodes()[0]
        this.queryForm.groupid = node.id
        this.queryData()
      },
      getAuthListAll() {
        getAuthList({}).then((res) => {
          this.authlist = res.data
          this.queryData()
        })
      },
      getGroupListData() {
        getGrouplist({})
          .then((res) => {
            this.nodes = res.data.map((item, index) => {
              let datac = {}
              datac.id = item.id
              datac.pid = ''
              datac.name = item.gname
              return datac
            })
            this.nodes.unshift({
              id: '',
              name: '总分组',
              pid: 0,
            })
            this.grouplist = res.data
          })
          .catch((ret) => {
            console.log(ret)
          })
      },
      addGroupHandle() {
        this.addGroupLoading = true
        if (this.info.gid) {
          editgroup(this.info)
            .then((res) => {
              this.showAddFenzu = false
              this.addGroupLoading = false
              this.info = {}
              this.getGroupListData()
            })
            .catch((ret) => {
              this.showAddFenzu = false
              this.addGroupLoading = false
            })
        } else {
          addGroup(this.info)
            .then((res) => {
              this.showAddFenzu = false
              this.addGroupLoading = false
              this.info = {}
              this.getGroupListData()
            })
            .catch((ret) => {
              this.showAddFenzu = false
              this.addGroupLoading = false
            })
        }
      },
      addHoverDom(treeid, treeNode) {
        const item = document.getElementById(`${treeNode.tId}_a`)
        if (
          item &&
          !item.querySelector('.tree_extra_btn') &&
          treeNode.id !== ''
        ) {
          const btn = document.createElement('sapn')
          btn.id = `${treeid}_${treeNode.id}_btn`
          btn.classList.add('tree_extra_btn')
          btn.innerText = '删除'

          const btn1 = document.createElement('sapn')
          btn1.id = `${treeid}_${treeNode.id}_btn_1`
          btn1.classList.add('m-r-15')
          btn1.classList.add('tree_extra_btn_1')
          btn1.innerText = '编辑'

          btn1.addEventListener('click', (e) => {
            e.stopPropagation()
            console.log(treeNode)
            this.clickEdit(treeNode)
          })

          btn.addEventListener('click', (e) => {
            e.stopPropagation()
            this.clickRemove(treeNode)
          })

          item.appendChild(btn1)

          item.appendChild(btn)
        }
      },
      removeHoverDom(treeid, treeNode) {
        const item = document.getElementById(`${treeNode.tId}_a`)
        if (item) {
          const btn = item.querySelector('.tree_extra_btn')
          if (btn) {
            item.removeChild(btn)
          }
          const btn1 = item.querySelector('.tree_extra_btn_1')
          if (btn1) {
            item.removeChild(btn1)
          }
        }
      },
      clickRemove(treeNode) {
        this.ztreeObj && this.ztreeObj.removeNode(treeNode)
        delGroup({ gid: treeNode.id })
          .then((res) => {
            this.$baseMessage(res.msg, 'success')
          })
          .catch((ret) => {
            this.$Message(ret.msg)
          })
      },
      handleCreated: function (ztreeObj) {
        this.ztreeObj = ztreeObj
        ztreeObj.expandNode(ztreeObj.getNodes()[0], true)
        this.ztreeObj.selectNode(this.ztreeObj.getNodes()[0], true)
      },
      onClick: function (evt, treeId, treeNode) {
        // 点击事件
        console.log(evt.type, treeNode)
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleEdit(row) {
        if (this.activeName == 1) {
          if (row.id) {
            this.$refs['edit'].showEdit(row)
          } else {
            let node = this.ztreeObj.getSelectedNodes()
            if (!node) return
            if (node.length == 0) {
              this.$alert('请先选择分组')
              return
            }
            this.$refs['edit'].showEdit({
              groupid: node[0].id,
              groupname: node[0].name,
            })
          }
        } else {
          if (row.id) {
            this.$refs['editChild'].showEdit(row)
          } else {
            let node = this.ztreeObj.getSelectedNodes()
            if (!node) return
            if (node.length == 0) {
              this.$alert('请先选择分组')
              return
            }
            this.$refs['editChild'].showEdit({
              groupid: node[0].id,
              groupname: node[0].name,
            })
          }
        }
      },
      clickEdit(info) {
        let infoc = this.grouplist.find((item) => item.id == info.id)
        this.info.gid = infoc.id
        this.info.groupname = infoc.gname
        this.info.note = infoc.detail

        this.showAddFenzu = true
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ jid: row.id })
            this.$baseMessage(msg, 'success')
            this.queryData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ jid })
              this.$baseMessage(msg, 'success')
              this.queryData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleDelete1(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await deluser({ uid: row.id })
            this.$baseMessage(msg, 'success')
            this.queryData()
          })
        }
      },

      queryData() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        if (this.activeName == '1') {
          const { data } = await getList(this.queryForm)
          this.list = data
          this.list = this.list.map((item) => {
            item.permissions = item.authids.split(',').map((bar) => {
              let er = this.authlist.find((e) => e.id == bar)
              return er.title
            })
            return item
          })
          setTimeout(() => {
            this.listLoading = false
          }, 300)
        } else {
          const { data } = await getUserlist(this.queryForm)
          this.list = data
          /**
           * fkList: [],
            hlList: [],
            zyzsList: [],
            marginList: [],
           */
          this.list = this.list.map((item) => {
            let group = this.grouplist.find((bar) => {
              return bar.id == item.group_id
            })

            if (group) {
              item.group = group.gname
            }

            let fkTemp = this.fkList.find((bar) => {
              return bar.id == item.wcmid
            })
            if (fkTemp) {
              console.log(fkTemp)
              item.fkTemp = fkTemp.name
            }
            let hlTemp = this.hlList.find((bar) => {
              return bar.id == item.ratemid
            })

            if (hlTemp) {
              item.hlTemp = hlTemp.name
            }

            let feeTemp = this.feeList.find((bar) => {
              return bar.id == item.feemid
            })

            if (feeTemp) {
              item.feeTemp = feeTemp.name
            }

            let marginTemp = this.marginList.find((bar) => {
              return bar.id == item.marginmid
            })

            if (marginTemp) {
              item.marginTemp = marginTemp.name
            }

            return item
          })
          setTimeout(() => {
            this.listLoading = false
          }, 300)
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  .minw300 {
    border: 1px solid #ebeef5;
    border-radius: 5px;
    min-width: 180px;
  }
  ::v-deep .c-ztree {
    height: calc(100vh - 250px);
    max-height: calc(100vh - 250px);
    overflow-y: auto;
    & > li {
      position: relative;
    }
  }
</style>
